<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Api\Controllers\Auths;

use App\Api\BaseApi;
use App\Models\BindAnAccount;
use App\Models\Cart;
use App\Models\CheckInApplication;
use App\Models\Footprint;
use App\Models\GroupOrderSetting;
use App\Models\PerformanceRecord;
use App\Models\Product;
use App\Models\RewardTransaction;
use App\Models\SignRecord;
use App\Models\SignRule;
use App\Models\User;
use App\Models\UserAddress;
use App\Models\UserBankCard;
use App\Models\UserRewardAccount;
use App\Models\WalletAccount;
use App\Models\Withdrawal;
use App\Models\WithdrawCashSetting;
use App\Service\Notifications\NotificationService;
use App\Service\Setting\BeanSettingService;
use App\Service\Setting\WithdrawCashSettingService;
use App\Service\Sms\SmsService;
use App\Service\Statistics\StatisticsService;
use App\Service\User\BeanAccountService;
use App\Service\User\RewardAccountService;
use App\Service\User\SignService;
use App\Service\User\UserServices;
use App\Service\User\WalletAccountService;
use App\Service\WithdrawCash\WithdrawCashService;
use Ramsey\Uuid\Rfc4122\UuidV4;

class UserApi extends BaseApi
{
    public function getUser()
    {
        $user = User::with([
            'performanceLevel',
            'userLevel',
            'address',
            'bank_card',
            'rewardAccount',
            'walletAccount',
            'beanAccount',
            'pointAccount',
            'voucher',
        ])
            ->select(['id',
                'name',
                'telephone',
                'profile',
                'default_bank_card_id',
                'member_level',
                'agent_level',
                'uuid',
                'contribution_value',
                'transaction_password',
                'inject_integral'
            ])
            ->find(self::UserId());
        return responses($user);
    }

    public function getAddress() //获取收货地址
    {
        $res = UserAddress::query()
            ->where('user_id', self::UserId())
            ->get();
        return responses($res);
    }

    public function addAddress() //添加收货地址
    {
        $request = self::validate([
            'consignee_name' => 'required|string',
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
            'province' => 'required|string',
            'city' => 'required|string',
            'district' => 'required|string',
            'address' => 'required|string',
            'postal_code',
            'is_default' => 'required|in:0,1',
        ]);
        $res = UserAddress::query()
            ->create([
                'user_id' => self::UserId(),
                'consignee_name' => $request->get('consignee_name'),
                'phone' => $request->get('phone'),
                'province' => $request->get('province'),
                'city' => $request->get('city'),
                'district' => $request->get('district'),
                'address' => $request->get('address'),
                'postal_code' => $request->get('postal_code', null),
                'is_default' => $request->get('is_default'),
            ]);
        return responses($res);
    }

    public function setDefaultAddress() //设置默认收货地址
    {
        $request = self::validate([
            'address_id' => 'required|integer',
        ]);
        $res = UserAddress::query()
            ->where('user_id', self::UserId())
            ->where('id', $request->get('address_id'))
            ->first();
        if (blank($res)) {
            return responses('无效的地址id', 7);
        }
        $res->is_default = 1;
        $res->save();
        return responses($res);
    }

    public function modifyAddress()  //修改收货地址
    {
        $request = self::validate([
            'address_id' => 'required|integer',
            'consignee_name' => 'required|string',
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
            'province' => 'required|string',
            'city' => 'required|string',
            'district' => 'required|string',
            'address' => 'required|string',
            'postal_code',
            'is_default' => 'required|in:0,1',
        ]);
        $userAddress = UserAddress::query()
            ->where('user_id', self::UserId())
            ->where('id', $request->get('address_id'))
            ->first();
        if (blank($userAddress)) {
            return responses('无效的地址id', 7);
        }
        $userAddress->consignee_name = $request->get('consignee_name');
        $userAddress->phone = $request->get('phone');
        $userAddress->province = $request->get('province');
        $userAddress->city = $request->get('city');
        $userAddress->district = $request->get('district');
        $userAddress->address = $request->get('address');
        $userAddress->postal_code = $request->get('postal_code', null);
        $userAddress->is_default = $request->get('is_default');
        $userAddress->save();
        return responses($userAddress);
    }

    public function deleteAddress()
    {
        $request = self::validate([
            'address_id' => 'required|integer',
        ]);
        $userAddress = UserAddress::query()
            ->where('user_id', self::UserId())
            ->where('id', $request->get('address_id'))
            ->first();
        $userAddress->delete();
        return responses('删除成功');
    }

    public function modifyProfilePicture() //修改头像
    {
        $request = self::validate([
            'profile' => 'required',
        ]);
        $user = self::UserModel();
        $user->profile = $request->get('profile');
        $user->save();
        return responses($user);
    }

    public function modifyLoginPassword() //修改登录密码
    {
        $request = self::validate([
            'sms_code' => 'required',
            'new_password' => 'required|min:8',
        ]);
        $user = self::UserModel();
        $sms = SmsService::make()->getSms($user->telephone);
        if ($sms != $request->get('sms_code')) {
            return responses('无效的验证码', 7);
        }

        $user->password = bcrypt($request->get('new_password'));
        $user->save();
        return responses('登录密码设置成功');
    }

    public function modifyNickName()
    {
        $request = self::validate([
            'nickname' => 'required|string',
        ]);
        $user = self::UserModel();
        $user->name = $request->get('nickname');
        $user->save();
        return responses($user);
    }

    public function modifyTransactionPassword() //修改交易密码
    {
        $request = self::validate([
            'sms_code' => 'required',
            'new_password' => 'required|min:8',
        ]);

        $user = self::UserModel();
        $sms = SmsService::make()->getSms($user->telephone);
        if ($sms != $request->get('sms_code')) {
            return responses('无效的验证码', 7);
        }
        if (blank($user->transaction_password)) {
            $user->transaction_password = bcrypt($request->get('new_password'));
            $user->save();
            return responses('交易密码设置成功');
        }

        $user->transaction_password = bcrypt($request->get('new_password'));
        $user->save();
        return responses('交易密码修改成功');
    }

    public function addToCart() //加入购物车
    {
        $request = self::validate([
            'product_id' => 'required|integer',
            'quantity' => 'required|integer|min:1',
            'sku' => 'required|array',
            'selected' => 'required|in:1,2',
        ]);
        $product = Product::query()
            ->where('status', 1)
            ->find($request->get('product_id'));
        if (! $product) {
            return responses('未找到该商品或该商品已下架', 7);
        }
        $productSku = $product->sku;
        [$key, $sku] = searchArrayInMulti($request->get('sku'), $productSku['sku'], ['stock']);
        if (! $sku) {
            return responses('无效的sku', 7);
        }

        $cart = Cart::query()->updateOrCreate([
            'user_id' => self::UserId(),
            'product_id' => $product->id,
        ], [
            'sku' => $sku,
            'quantity' => $request->get('quantity'),
            'price' => $sku['member_price'],
            'selected' => $request->get('selected'),
            'is_valid' => 1,
        ]);
        return responses($cart);
    }

    public function deleteCart() //删除购物车
    {
        $request = self::validate([
            'ids' => 'required|array',
        ]);
        Cart::query()
            ->whereIn('id', $request->get('ids'))
            ->where('user_id', self::UserId())
            ->delete();
        return responses('删除成功');
    }

    public function myCarts()
    {
        $res = Cart::with(['product' => function ($query) {
            $query->select(['name', 'id', 'subtitle', 'main_image', 'sold_num']);
        }])
            ->where('user_id', self::UserId())
            ->simplePaginate(request()->get('perPage', 10));
        return responses($res);
    }

    public function notifyCount()
    {
        return responses(NotificationService::make()->getNotifyCount(self::UserModel()));
    }

    public function getNotify()
    {
        $request = self::validate([
            'type' => 'required|in:1,2,3',
        ]);
        $type = $request->get('type');
        return responses(NotificationService::make()->getNotify(self::UserModel(), $type));
    }

    public function readNotify()
    {
        $request = self::validate([
            'ids' => 'required|array',
        ]);
        NotificationService::make()->readNotify(self::UserModel(), $request->get('ids'));
        return responses('成功');
    }

    public function readAllNotify()
    {
        $request = self::validate([
            'type' => 'required|in:1,2,3',
        ]);
        $type = $request->get('type');
        NotificationService::make()->allRead(self::UserModel(), $type);
        return responses('成功');
    }

    public function myFan()
    {
        $user = self::UserModel();
        return responses(StatisticsService::make()->myFan($user));
    }

    public function teamCenter()
    {
//        $user = User::query()->find(9);
        $user = self::UserModel();
        return responses(StatisticsService::make()->teamCenter($user));
    }

    public function incomeDetails()
    {
        $user = self::UserModel();
        $trans = RewardTransaction::query()
            ->where('user_id', $user->id)
            ->latest()
            ->simplePaginate(request()->get('perPage', 10));
        return responses($trans);
    }

    public function bindBankCard()
    {
        $request = self::validate([
            'bank_name' => 'required|string',
            'bank_branch' => 'string|required',
            'card_type' => 'required|in:1,2,3',
            'card_number' => 'required|string',
            'card_holder' => 'required|string',
            'id_card_number' => 'string',
            'phone' => 'required',
        ]);
        UserBankCard::query()->Create([
            'user_id' => self::UserId(),
            'bank_name' => $request->get('bank_name'),
            'bank_branch' => $request->get('bank_branch'),
            'card_type' => $request->get('card_type'),
            'card_number' => $request->get('card_number'),
            'card_holder' => $request->get('card_holder'),
            'id_card_number' => $request->get('id_card_number'),
            'phone' => $request->get('phone'),
        ]);
        return responses('绑定成功');
    }

    public function updateBankCard()
    {
        $request = self::validate([
            'id' => 'required|integer',
        ]);
        $id = $request->get('id');
        $updateData = $request->except('id');
        $res = UserBankCard::query()
            ->where('user_id', self::UserId())
            ->where('id', $id)
            ->first();
        $res->update($updateData);
        return responses($res->refresh());
    }

    public function deleteBankCard()
    {
        $request = self::validate([
            'id' => 'required|integer',
        ]);
        $id = $request->get('id');
        $res = UserBankCard::query()
            ->where('user_id', self::UserId())
            ->where('id', $id)
            ->delete();
        return responses($res);
    }

    public function defaultBankCard()
    {
        $request = self::validate([
            'id' => 'required|integer',
        ]);
        $id = $request->get('id');
        $res = UserBankCard::query()
            ->where('user_id', self::UserId())
            ->where('id', $id)
            ->first();
        if (! $res) {
            return responses('无效的银行卡', 7);
        }
        $res->is_default = 1;
        $user = self::UserModel();
        $user->default_bank_card_id = $id;
        $user->save();
        $res->save();
        return responses('设置默认银行卡成功');
    }

    public function BankCardList()
    {
        $user = self::UserModel();
        $res = UserBankCard::query()
            ->where('user_id', self::UserId())
            ->get();

        return responses($res);
    }

    public function withdrawCash() //提现
    {
        $request = self::validate([
            'type' => 'required|in:1,2,3',
            'amount' => 'required',
        ]);
        $user = self::UserModel();
        $this->transaction_password($user);
        $type = $request->get('type');
        $amount = $request->get('amount');

        $userRewardAccount = UserRewardAccount::query()->where('user_id', self::UserId())->first();
        $contribution_value = WithdrawCashSettingService::make()->getSetting('contribution_value');
        if ($user->contribution_value < $contribution_value) {
            return responses('贡献值不足，提现失败', 7);
        }
        if ($userRewardAccount->available_balance < $amount) {
            return responses('当前奖励账户金额不足', 7);
        }
        if ($amount <= 0) {
            return responses('金额不能小于等于0', 7);
        }
        switch ($type) {
            case 1:
                if ($user->default_bank_card_id == 0) {
                    return responses('没有绑定提现银行卡', 7);
                }
                if ($amount > 5000) {
                    return responses('提现金额最大为5000', 7);
                }
                if ($amount % 100 != 0) {
                    return responses('提现金额必须为100的倍数', 7);
                }
                $res = WithdrawCashService::make()->withdrawCash($user, $amount);
                break;
            case 2:
                $res = WithdrawCashService::make()->withdrawMoneyToTheWallet($user, $amount);
                break;
            case 3:
                $toUser = User::query()
                    ->where('telephone', $request->get('telephone'))
                    ->first();

                if (blank($toUser)) {
                    return responses('无效的转账手机号码', 7);
                }
                $res = WithdrawCashService::make()->withdrawMoneyToOthers($user, $amount, $toUser);
                break;
        }
        if ($res['error']) {
            return responses($res['msg'], 7);
        }
        return responses($res['msg']);
    }

    public function transferDetails()
    {
        $model = RewardTransaction::query()
            ->where('user_id', self::UserId())
            ->where('transaction_type', 4)
            ->where('change_type', 2)->get();

        $res = RewardTransaction::query()
            ->where('user_id', self::UserId())
            ->where('transaction_type', 4)
//            ->where('change_type', 2)
            ->paginate(request()->get('perPage', 10));
        return responses([
            'the_total' => $model->sum('amount'),
            'today' => $model->where('created_at', '>', now()->startOfDay()->toDateTimeString())->sum('amount'),
            'list' => $res,
        ]);
    }

    public function walletToReward()//钱包到奖励余额
    {
        $request = self::validate([
            'amount' => 'required',
        ]);
        $user = self::UserModel();
        $this->transaction_password($user);
        $amount = $request->get('amount');
        $userWalletAccount = WalletAccount::query()
            ->where('user_id', self::UserId())
            ->first();
        $contribution_value = WithdrawCashSettingService::make()->getSetting('contribution_value');
        if ($user->contribution_value < $contribution_value) {
            return responses('贡献值不足，转换失败', 7);
        }
        if ($userWalletAccount->balance < $amount) {
            return responses('当前钱包账户金额不足', 7);
        }
        $withdrawCashSetting = WithdrawCashSetting::query()->first();
        $fee = $withdrawCashSetting->transfer_wallet_fee;
        $bean = $withdrawCashSetting->transfer_wallet_bean;
        if ($bean > 0) {
            $bean = bcmul($bean, $amount, 2);
            $msg = '转账到奖励余额消耗KC通证:' . $bean;
            $flag = BeanAccountService::make()
                ->consumption($user->id, $bean, $msg);
            if (! $flag) {
                return responses('转账所需KC通证不足！');
            }
            BeanSettingService::make()->increaseTheAmountOfCombustion($bean, $msg);
        }
        $fee = bcmul($amount, $fee, 2);
        $nowAmount = bcsub($amount, $fee, 2);
        $msg = sprintf('转账到奖励余额 金额:%s 手续费:%s 实际到账%s', $amount, $fee, $nowAmount);

        WalletAccountService::make()->consumption(
            $user->id,
            $amount,
            $msg,
            4
        );
        RewardAccountService::make()->recharge(
            $user->id,
            $nowAmount,
            4,
            sprintf('收到钱包转账 金额:%s 手续费:%s 实际到账%s', $amount, $fee, $nowAmount)
        );
        return responses($msg);
    }

    public function withdrawCashRecord() //提现记录
    {
        $res = Withdrawal::query()
            ->where('user_id', self::UserId())
            ->latest()
            ->simplePaginate(request('perPage', 10));
        return responses($res);
    }

    public function withdrawCashSetting()
    {
        $request = self::validate([
            'type' => 'required|in:1,2,3',
        ]);

        $res = WithdrawCashService::make()->getWithdrawCashSetting($request->get('type'));
        return responses($res);
    }

    public function rewardRecord()
    {
        $res = PerformanceRecord::query()
            ->where('user_id', self::UserId())
            ->latest()
            ->simplePaginate(request()->get('perPage', 10));
        return responses($res);
    }

    public function merchantSettlement()//商家入驻
    {
        $request = self::validate([
            'company_name' => 'required',
            'license_image' => 'required',
            'contact_phone' => 'required',
            'product_type' => 'required',
        ]);
        CheckInApplication::query()->Create([
            'user_id' => self::UserId(),
            'company_name' => $request->get('company_name'),
            'license_image' => $request->get('license_image'),
            'contact_phone' => $request->get('contact_phone'),
            'product_type' => $request->get('product_type'),
            'status' => 1,
        ]);
        return responses('已提交入驻申请！');
    }

    public function footprint()
    {
        $res = Footprint::with('product')
            ->where('user_id', self::UserId())
            ->simplePaginate(request()->get('perPage', 10));
        return responses($res);
    }

    public function getSignRecord()
    {
        $signRule = SignRule::query()->first();
        $record = SignRecord::query()
            ->where('user_id', self::UserId())
            ->get();

        return responses([
            'sign_rule' => $signRule,
            'record' => $record,
        ]);
    }

    public function userSign()
    {
        $res = SignService::make()->sign(self::UserModel());
        if ($res['success']) {
            return responses($res);
        }
        return responses($res, 7);
    }

    public function setting()
    {
        $pre_sale = GroupOrderSetting::query()->first()->pre_sale;
        $res = [
            'pre_sale' => $pre_sale,
        ];

        return response($res);
    }

    public function turningBeans() //转豆
    {
        $request = self::validate([
            'amount' => 'required',
            'to_telephone' => 'required',
            // 'message'=>'required',
        ]);
        $user = self::UserModel();
        $this->transaction_password($user);
        $amount = $request->get('amount');
        $message = $request->get('message', '没有消息');
        $toUser = User::query()
            ->where('telephone', $request->get('to_telephone'))
            ->first();
        if (blank($toUser)) {
            return responses('无效的手机号码', 7);
        }
        // 是否$ancestor的下级
        if (! $toUser->isDescendantOf($user)) {
            return responses('不是你的下级,转豆失败', 7);
        }
        // 是否$parent的直接下级
//        if (!$toUser->isChildOf($user)){
//            return responses('不是你的直接下级,转豆失败', 7);
//        }
        $rage = 0.03;
        $camount = bcmul($amount, $rage, 2);
        $totalAmount = bcadd($amount, $camount, 2);
        if (BeanAccountService::make()->checkTheBalance($user->id) < $totalAmount) {
            return responses('KC通证余额不足,转账失败', 7);
        }

        $msg = sprintf('转KC通证给下级用户%s 数量:%s 燃烧:%s 汇总:%s 原因:%s', $toUser->telephone, $amount, $camount, $totalAmount, $message);
        $msg2 = sprintf('收到上级用户%s 转KC通证 数量:%s 原因:%s', $user->telephone, $amount, $message);

        BeanSettingService::make()->increaseTheAmountOfCombustion($camount, $msg);

        BeanAccountService::make()
            ->consumption($user->id, $totalAmount, $msg, 5);
        BeanAccountService::make()
            ->recharge($toUser->id, $amount, $msg2, false, 5);
        return responses($msg);
    }

    public function BindAnAccount() //绑定账户
    {
        $request = self::validate([
            'telephone' => 'required',
            'password' => 'required',
        ]);
        $myBind = BindAnAccount::query()->firstOrCreate([
            'user_id' => self::UserId(),
        ], [
            'uuid' => UuidV4::uuid1(self::UserId())->toString(),
        ]);
        $Myuuid = $myBind->uuid;
        $bindUser = User::query()->where('telephone', $request->get('telephone'))->first();

        if (blank($bindUser)) {
            return responses('该手机号未注册', 7);
        }
        if ($bindUser->id == self::UserId()) {
            return responses('不能绑定自己', 7);
        }
        if (password_verify($request->get('password'), $bindUser->password)) {
            $newBindAccount = BindAnAccount::query()->firstOrCreate([
                'user_id' => $bindUser->id,
            ], [
                'uuid' => $Myuuid,
            ]);
            if ($newBindAccount->wasRecentlyCreated) {
                return responses('该账户绑定成功');
            }
            return responses('该账户已被绑定,绑定失败', 7);
        }
        return responses('手机号或密码错误', 7);
    }

    public function SelectAnAccount() //选择账户
    {
        $request = self::validate([
            'telephone' => 'required',
        ]);
        $myBind = BindAnAccount::query()->where(
            'user_id',
            self::UserId()
        )->first();
        $Myuuid = $myBind->uuid ?? -1;
        $bindUser = User::query()->where('telephone', $request->get('telephone'))->first();

        if (blank($bindUser)) {
            return responses('该手机号未注册', 7);
        }
        $band = BindAnAccount::query()->where('user_id', $bindUser->id)->first();
        if ($Myuuid == $band->uuid ?? 0) {
            $bindUser['token'] = $this->generateToken($bindUser);
            return responses($bindUser);
        }
        return responses('该手机号未绑定到你账户', 7);
    }

    public function getAnAccount()
    {
        $myBind = BindAnAccount::query()->where(
            'user_id',
            self::UserId()
        )->first();
        $Myuuid = $myBind->uuid ?? -1;
        if ($Myuuid != -1) {
            $res = BindAnAccount::with('user')
                ->where('user_id', '<>', self::UserId())
                ->where('uuid', $Myuuid)->get();
            return responses($res);
        }
        return responses([]);
    }//获取我的绑定

    public function deleteAnAccount()
    {
        $request = self::validate([
            'telephone' => 'required',
        ]);
        $myBind = BindAnAccount::query()->where(
            'user_id',
            self::UserId()
        )->first();
        $Myuuid = $myBind->uuid ?? -1;

        $bindUser = User::query()->where('telephone', $request->get('telephone'))->first();

        if (blank($bindUser)) {
            return responses('该手机号未注册', 7);
        }
        $band = BindAnAccount::query()->where('user_id', $bindUser->id)->first();
        if ($Myuuid == $band->uuid ?? 0) {
            $band->delete();
            return responses('删除成功');
        }
        return responses('该手机号未绑定到你账户', 7);
    }

    public function systemText()
    {
        UserServices::make()->reconstructTheBenefits();
        return responses('成功');
    }
}
